package com.sanbi.common.util.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sanbi.common.util.DateUtil;
import com.sanbi.common.util.NumberUtil;
import com.sanbi.common.vo.Enums;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @desc jwt token 辅助工具
 * @author wanggang
 * @time 2024/9/12 11:39
 */
@Slf4j
public class JwtHelper {
	// token秘钥
	static final String Token_Secret = "9254c11775c642b684f7bdf54f51fdb6";
	// 签名生成人
	static final String ISSUSER = "uno-middleware";
	// 签名的主题
	static final String SUBJECT = "this is unouno middleware token";
	// 签名的观众
	static final String AUDIENCE = "unouno";

	public String createToken(long userId){
		try {
		    Algorithm algorithm = Algorithm.HMAC256(Token_Secret);
		    Map<String, Object> map = new HashMap<String, Object>();
		    Date nowDate = new Date();
			// 过期时间：180 天
			Date expireDate = getAfterDate(nowDate,0,0,180,0,0,0);
	        map.put("alg", "HS256");
	        map.put("typ", "JWT");
		    String token = JWT.create()
		    	// 设置头部信息 Header
		    	.withHeader(map)
		    	// 设置 载荷 Payload
		    	.withClaim("userId", userId)
//		        .withIssuer(ISSUSER)
//		        .withSubject(SUBJECT)
//		        .withAudience(AUDIENCE)
		        // 生成签名的时间
		        .withIssuedAt(nowDate)
		        // 签名过期的时间
		        .withExpiresAt(expireDate)
		        // 签名 Signature
		        .sign(algorithm);
		    return token;
		} catch (JWTCreationException ex){
			log.error("Creating token failed: {}",ex.getMessage());
			return null;
		}
	}

	public String createToken(long userId, Enums.TokenTypeEnum tokenTypeEnum){
		try {
			Algorithm algorithm = Algorithm.HMAC256(Token_Secret);
			Map<String, Object> map = new HashMap<String, Object>();
			Date nowDate = new Date();
			Date expireDate = getAfterDate(nowDate,0,0,tokenTypeEnum.getExpiredTime(),0,0,0);
			map.put("alg", "HS256");
			map.put("typ", "JWT");
			String token = JWT.create()
					// 设置头部信息 Header
					.withHeader(map)
					// 设置 载荷 Payload
					.withClaim("userId", userId)
//		        .withIssuer(ISSUSER)
//		        .withSubject(SUBJECT)
//		        .withAudience(AUDIENCE)
					// 生成签名的时间
					.withIssuedAt(nowDate)
					// 签名过期的时间
					.withExpiresAt(expireDate)
					// 签名 Signature
					.sign(algorithm);
			return token;
		} catch (JWTCreationException ex){
			log.error("Creating token failed: {}",ex.getMessage());
			return null;
		}
	}

	public Date getExpireTime(String token) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(Token_Secret);
			JWTVerifier verifier = JWT.require(algorithm)
//					.withIssuer(ISSUSER)
					.build();
			DecodedJWT jwt = verifier.verify(token);

			return jwt.getExpiresAt();
		} catch (JWTVerificationException ex){
			log.error("invalid token: {}",ex.getMessage());
			return null;
		}
	}

	public Long verifyTokenAndGetUserId(String token) {
		try {
		    Algorithm algorithm = Algorithm.HMAC256(Token_Secret);
		    JWTVerifier verifier = JWT.require(algorithm)
//		        .withIssuer(ISSUSER)
		        .build();
		    DecodedJWT jwt = verifier.verify(token);
		    Map<String, Claim> claims = jwt.getClaims();
		    Claim claim = claims.get("userId");
		    return claim.asLong();
		} catch (JWTVerificationException ex){
			log.error("invalid token: {}",ex.getMessage());
		}catch (Exception ex){
			log.error("invalid token: {}",ex.getMessage());
		}

		return null;
	}

	private Date getAfterDate(Date date, int year, int month, int day, int hour, int minute, int second){
		if(date == null){
			date = new Date();
		}

		Calendar cal = new GregorianCalendar();
		cal.setTime(date);
		if(year != 0){
			cal.add(Calendar.YEAR, year);
		}
		if(month != 0){
			cal.add(Calendar.MONTH, month);
		}
		if(day != 0){
			cal.add(Calendar.DATE, day);
		}
		if(hour != 0){
			cal.add(Calendar.HOUR_OF_DAY, hour);
		}
		if(minute != 0){
			cal.add(Calendar.MINUTE, minute);
		}
		if(second != 0){
			cal.add(Calendar.SECOND, second);
		}
		return cal.getTime();
	}

	public static void main(String[] args) {
		JwtHelper jwtHelper=new JwtHelper();
		long userId=DateUtil.getCurrentTimestampNumber();
		System.out.println("userId: "+userId);

//		String token=jwtHelper.createSaleToken(userId);
		String token=jwtHelper.createToken(userId);
		System.out.println("token: "+token);

		Date expireTime=jwtHelper.getExpireTime(token);
		System.out.println("expire time: "+expireTime);
	}

}
